import 'package:flutter/material.dart';
import '../../models/product_template.dart';
import '../../services/database_helper.dart';
import '../../core/app_theme.dart';
import '../../core/snackbar_helper.dart';
import 'add_edit_template_screen.dart';

class ProductTemplateManagementScreen extends StatefulWidget {
  const ProductTemplateManagementScreen({super.key});

  @override
  State<ProductTemplateManagementScreen> createState() => _ProductTemplateManagementScreenState();
}

class _ProductTemplateManagementScreenState extends State<ProductTemplateManagementScreen> {
  List<ProductTemplate> _templates = [];
  Map<String, List<ProductTemplate>> _categorizedTemplates = {};
  Map<String, bool> _categoryExpansionState = {};
  Map<String, bool> _categorySelectionState = {};
  Map<int, bool> _selectedTemplates = {};
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _loadTemplates();
  }

  Future<void> _loadTemplates() async {
    try {
      final dbHelper = DatabaseHelper();
      final templates = await dbHelper.getProductTemplates();
      setState(() {
        _templates = templates;
        _categorizedTemplates = _categorizeTemplates(templates);
        _categoryExpansionState = _initializeExpansionState();
        _categorySelectionState = _initializeCategorySelectionState();
        _selectedTemplates = _initializeSelectionState(templates);
        _isLoading = false;
      });
    } catch (e) {
      print('加载商品模板失败: $e');
      SnackbarHelper.showError(context, '加载模板失败: $e');
      setState(() {
        _isLoading = false;
      });
    }
  }

  Map<String, List<ProductTemplate>> _categorizeTemplates(List<ProductTemplate> templates) {
    final Map<String, List<ProductTemplate>> categorized = {};
    for (var template in templates) {
      if (!categorized.containsKey(template.category)) {
        categorized[template.category] = [];
      }
      categorized[template.category]!.add(template);
    }
    return categorized;
  }

  Map<String, bool> _initializeExpansionState() {
    final Map<String, bool> state = {};
    for (var category in _categorizedTemplates.keys) {
      state[category] = false;
    }
    return state;
  }

  Map<String, bool> _initializeCategorySelectionState() {
    final Map<String, bool> state = {};
    for (var category in _categorizedTemplates.keys) {
      state[category] = false;
    }
    return state;
  }

  Map<int, bool> _initializeSelectionState(List<ProductTemplate> templates) {
    final Map<int, bool> state = {};
    for (var i = 0; i < templates.length; i++) {
      state[i] = false;
    }
    return state;
  }

  void _toggleCategoryExpansion(String category) {
    setState(() {
      _categoryExpansionState[category] = !_categoryExpansionState[category]!;
    });
  }

  void _toggleTemplateSelection(int index, bool? value) {
    setState(() {
      _selectedTemplates[index] = value ?? false;
    });
  }

  void _toggleCategorySelection(String category, bool? value) {
    setState(() {
      _categorySelectionState[category] = value ?? false;
      
      // 选中/取消选中该分类下的所有模板
      final templatesInCategory = _categorizedTemplates[category]!;
      for (var template in templatesInCategory) {
        final index = _templates.indexOf(template);
        if (index != -1) {
          _selectedTemplates[index] = value ?? false;
        }
      }
    });
  }

  void _toggleAllSelection(bool? value) {
    setState(() {
      for (var category in _categorizedTemplates.keys) {
        _categorySelectionState[category] = value ?? false;
      }
      for (var i = 0; i < _templates.length; i++) {
        _selectedTemplates[i] = value ?? false;
      }
    });
  }

  bool _isCategoryAllSelected(String category) {
    final templatesInCategory = _categorizedTemplates[category]!;
    return templatesInCategory.every((template) {
      final index = _templates.indexOf(template);
      return _selectedTemplates[index] == true;
    });
  }

  Future<void> _deleteSelectedTemplates() async {
    final selectedTemplates = <ProductTemplate>[];
    for (var i = 0; i < _templates.length; i++) {
      if (_selectedTemplates[i] == true) {
        selectedTemplates.add(_templates[i]);
      }
    }

    if (selectedTemplates.isEmpty) {
      SnackbarHelper.showError(context, '请至少选择一个模板');
      return;
    }

    try {
      final dbHelper = DatabaseHelper();
      for (var template in selectedTemplates) {
        await dbHelper.deleteProductTemplate(template.id!);
      }
      
      SnackbarHelper.showSuccess(context, '已删除 ${selectedTemplates.length} 个模板');
      await _loadTemplates(); // 重新加载
    } catch (e) {
      SnackbarHelper.showError(context, '删除失败: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    final selectedCount = _selectedTemplates.values.where((selected) => selected).length;
    final totalCount = _templates.length;

    return Scaffold(
      appBar: AppBar(
        title: const Text('商品模板管理', style: AppTheme.titleLarge),
        actions: [
          if (selectedCount > 0)
            IconButton(
              icon: const Icon(Icons.delete),
              onPressed: _deleteSelectedTemplates,
              tooltip: '删除选中模板',
            ),
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => const AddEditTemplateScreen(),
                ),
              ).then((_) => _loadTemplates());
            },
          ),
        ],
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : _templates.isEmpty
              ? Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      const Text(
                        '暂无商品模板',
                        style: AppTheme.bodyLarge,
                      ),
                      const SizedBox(height: 16),
                      ElevatedButton(
                        onPressed: () {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => const AddEditTemplateScreen(),
                            ),
                          ).then((_) => _loadTemplates());
                        },
                        child: const Text('添加第一个模板'),
                      ),
                    ],
                  ),
                )
              : Column(
                  children: [
                    // 全选按钮
                    Container(
                      padding: const EdgeInsets.all(16),
                      color: Colors.grey[100],
                      child: Row(
                        children: [
                          Checkbox(
                            value: selectedCount == totalCount && totalCount > 0,
                            onChanged: _toggleAllSelection,
                          ),
                          const Text('全选', style: AppTheme.bodyLarge),
                          const Spacer(),
                          Text(
                            '已选: $selectedCount/$totalCount 个',
                            style: AppTheme.bodyMedium,
                          ),
                        ],
                      ),
                    ),
                    // 分类列表
                    Expanded(
                      child: ListView(
                        children: _categorizedTemplates.keys.map((category) {
                          return _buildCategorySection(category);
                        }).toList(),
                      ),
                    ),
                  ],
                ),
    );
  }

  Widget _buildCategorySection(String category) {
    final templatesInCategory = _categorizedTemplates[category]!;
    final isExpanded = _categoryExpansionState[category] ?? false;
    final isAllSelected = _isCategoryAllSelected(category);

    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
      child: Column(
        children: [
          // 分类标题
          ListTile(
            leading: const Icon(Icons.category, color: Colors.blue),
            title: Text('$category (${templatesInCategory.length})', style: AppTheme.bodyLarge),
            trailing: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Checkbox(
                  value: isAllSelected,
                  onChanged: (value) => _toggleCategorySelection(category, value),
                ),
                IconButton(
                  icon: Icon(
                    isExpanded ? Icons.expand_less : Icons.expand_more,
                    color: Colors.grey,
                  ),
                  onPressed: () => _toggleCategoryExpansion(category),
                ),
              ],
            ),
            onTap: () => _toggleCategoryExpansion(category),
          ),
          // 分类内容
          if (isExpanded)
            Column(
              children: templatesInCategory.map((template) {
                final index = _templates.indexOf(template);
                return ListTile(
                  leading: Checkbox(
                    value: _selectedTemplates[index] ?? false,
                    onChanged: (value) => _toggleTemplateSelection(index, value),
                  ),
                  title: Text(template.name, style: AppTheme.bodyLarge),
                  subtitle: Text(
                    '${template.defaultSpec} | ¥${template.defaultPrice.toStringAsFixed(2)}',
                    style: AppTheme.bodyMedium,
                  ),
                  trailing: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      IconButton(
                        icon: const Icon(Icons.edit, color: Colors.blue),
                        onPressed: () {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => AddEditTemplateScreen(
                                template: template,
                              ),
                            ),
                          ).then((_) => _loadTemplates());
                        },
                      ),
                      IconButton(
                        icon: const Icon(Icons.delete, color: Colors.red),
                        onPressed: () => _showDeleteDialog(context, template),
                      ),
                    ],
                  ),
                );
              }).toList(),
            ),
        ],
      ),
    );
  }

  void _showDeleteDialog(BuildContext context, ProductTemplate template) {
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('确认删除', style: AppTheme.titleMedium),
        content: Text(
          '确定要删除模板"${template.name}"吗？',
          style: AppTheme.bodyMedium,
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(ctx).pop(),
            child: const Text('取消', style: AppTheme.bodyMedium),
          ),
          TextButton(
            onPressed: () async {
              Navigator.of(ctx).pop();
              await _deleteSingleTemplate(template);
            },
            child: const Text('删除', style: TextStyle(fontSize: 18, color: Colors.red)),
          ),
        ],
      ),
    );
  }

  Future<void> _deleteSingleTemplate(ProductTemplate template) async {
    try {
      final dbHelper = DatabaseHelper();
      await dbHelper.deleteProductTemplate(template.id!);
      
      SnackbarHelper.showSuccess(context, '已删除模板"${template.name}"');
      await _loadTemplates(); // 重新加载
    } catch (e) {
      SnackbarHelper.showError(context, '删除失败: $e');
    }
  }
}